package icu.cocoon.mail.service;


import icu.cocoon.mail.entity.Mail;
import java.io.File;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * @author Cocoon
 */
@Slf4j
@Service
public class MailService {

  @Resource
  private JavaMailSenderImpl javaMailSender;


  public void sendMail(Mail mail, String attachmentFilename, File file) {
    javaMailSender.setPassword(mail.getMailPassword());
    javaMailSender.setUsername(mail.getMailUsername());
    try {
      MimeMessageHelper helper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
      helper.setTo(mail.getToList().toArray(new String[0]));
      if (CollectionUtils.isNotEmpty(mail.getCcList())) {
        helper.setCc(mail.getCcList().toArray(new String[0]));
      }
      helper.setSubject(mail.getSubject());
      helper.setText(mail.getContent());
      helper.setFrom(mail.getMailUsername());
      helper.addAttachment(attachmentFilename, new FileSystemResource(file));
      javaMailSender.send(helper.getMimeMessage());

    } catch (MessagingException e) {
      throw new MailParseException(e);
    }
  }

}
